package com.atguigu.gulimall.seckill.servcie.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.servcie.SeckillSkuService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionsWithSkus;
import com.atguigu.gulimall.seckill.vo.SeckillSkuVo;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.asn1.esf.SPuri;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import sun.plugin.util.UIUtil;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SeckillSkuServiceImpl implements SeckillSkuService{

    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedissonClient redissonClient;

    private static final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";

    private static final String SKUKILL_CACHE_PREFIX = "seckill:skus:";

    private static final String SKU_STOCK_SEMAPHORE = "seckill:stock:";
    @Override
    public void uploadSeckillSkuLatest3Days() {
        // 需要扫描参与秒杀的活动
        R lates3DaySession = couponFeignService.getLates3DaySession();
        if(lates3DaySession.getCode() == 0){
            List<SeckillSessionsWithSkus> data = lates3DaySession.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            // 缓存到redis里
            // 缓存活动信息
            saveSessionInfos(data);
            // 缓存商品信息
            saveSessionSkuInfos(data);

        }

    }

    public List<SeckillSkuRedisTo> blockHandler(BlockException e){

        log.error("getCurrentSeckillSkus被限流了...");
        return null;
    }

    /**
     * 返回当前时间参与的秒杀商品
     * @return
     */
    @SentinelResource(value = "getCurrentSeckillSkus", blockHandler = "blockHandler")
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        // 1、确定当前时间处于哪个秒杀场次
        long time = System.currentTimeMillis();
            Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            for (String key : keys) {
                String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                Long start = Long.parseLong(s[0]);
                Long end = Long.parseLong(s[1]);
                if(time >= start && time <= end){

                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> ops =
                            redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = ops.multiGet(range);
                    if(list != null){
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo redisTo = JSON.parseObject((String) item, SeckillSkuRedisTo.class);
                            // 当前秒杀开始了，需要展示随机码
                            redisTo.setRandomCode(null);
                            return redisTo;
                        }).collect(Collectors.toList());

                        return collect;
                    }
                    break;
                }
            }


        // 2、获取秒杀场次的所有商品信息
        return null;
    }

    /**
     * 获取某个商品的秒杀信息
     * @param skuId
     * @return
     */
    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        // 找到所有需要参与秒杀的商品key
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if(keys != null){
            for (String key : keys) {
                if(key.indexOf("_"+skuId) > -1){
                    String s = ops.get(key);
                    SeckillSkuRedisTo skuRedisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);
                    // 判断当前是时间是秒杀时间
                    long current = System.currentTimeMillis();
                    if(current >= skuRedisTo.getStartTime() && current < skuRedisTo.getEndTime()){

                    }else{
                        skuRedisTo.setRandomCode(null);
                    }

                    return skuRedisTo;

                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        // 获取秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if(StringUtils.isEmpty(json)){
            return null;
        }else{
            SeckillSkuRedisTo redis = JSON.parseObject(json, SeckillSkuRedisTo.class);
            // 校验时间
            long now = System.currentTimeMillis();
            if(! (now >= redis.getStartTime() && now <= redis.getEndTime())){
                return null;
            }
            // 校验随机码和商品ID是否匹配
            String randomCode = redis.getRandomCode();
            String skuId = redis.getPromotionSessionId()+"_"+redis.getSkuId();
            if(! (key.equals(randomCode) && killId.equals(skuId))){

                return null;
            }
            // 校验数量是否合法
            if(num > redis.getSeckillLimit().intValue()){
                return null;
            }
            // 验证此人是秒杀过
            long ttl = redis.getEndTime() - now;
            String redisKey = memberRespVo.getId().toString() + "_" + skuId;
            Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
            if(aBoolean == null || aBoolean == false){
                return null;
            }

            // 获取分布式信号量
            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
            try {
                boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                if(b == false){
                    return null;
                }
                // 快速下单，发送mq
                String timeId = IdWorker.getTimeId();
                SeckillOrderTo orderTo = new SeckillOrderTo();
                orderTo.setOrderSn(timeId);
                orderTo.setMemberId(memberRespVo.getId());
                orderTo.setNum(num);
                orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                orderTo.setSeckillPrice(redis.getSeckillPrice());
                orderTo.setSkuId(redis.getSkuId());
                rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order", orderTo);
                return timeId;

            } catch (InterruptedException e) {
                e.printStackTrace();
                return null;
            }

        }

    }

    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessions){

        if(sessions == null)
            return;
        sessions.stream().forEach(session->{
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean hasKey = redisTemplate.hasKey(key);
            if(! hasKey){
                List<String> collect = session.getRelationSkus().stream().map(item->
                        item.getPromotionSessionId()+"_"+item.getSkuId()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, collect);
            }

        });
    }
    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessions){
        if(sessions == null)
            return;

        sessions.stream().forEach(session -> {
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                // 设置商品随机码
                String token = UUID.randomUUID().toString().replace("-","");
                if(! ops.hasKey(seckillSkuVo.getPromotionSessionId()+"_"+seckillSkuVo.getSkuId())){
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();

                    // sku的基本信息
                    R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if(skuInfo.getCode() == 0){
                        SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfo(info);
                    }

                    // sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, redisTo);

                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());


                    redisTo.setRandomCode(token);

                    // 保存到redis
                    String jsonString = JSON.toJSONString(redisTo);
                    ops.put(seckillSkuVo.getPromotionSessionId()+"_"+seckillSkuVo.getSkuId(), jsonString);
                    // 设置信号量用来限流
                    // 如果当前场次的商品库存信息已经上架，就不需要上架
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                }

            });

        });
    }
}
